package com.ezgo.erc.master.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ezgo.erc.master.utils.Constants;
import com.ezgo.erc.master.utils.StringUtil;
import com.ezgo.erc.utils.SysLogUtil;
import com.ezgo.erc.utils.UserUtil;

/**
 * 
 * (拦截器)模块 TODO(访问拦截规则)
 * 
 * @author devintam
 * @date 2015年7月13日 下午12:49:24
 *
 */
public class UrlCheckInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) throws Exception {

		String requestRri = request.getRequestURI();
		String uriPrefix = request.getContextPath();
		if ((StringUtil.startsWith(requestRri, uriPrefix) && (StringUtil.endsWith(requestRri, "/save") || StringUtil.endsWith(requestRri, "/update")
				|| StringUtil.endsWith(requestRri, "/list") || StringUtil.endsWith(requestRri, "/view") || StringUtil.endsWith(requestRri, "/form")
				|| StringUtil.endsWith(requestRri, "/delete") || StringUtil.endsWith(requestRri, "/import")
				|| StringUtil.endsWith(requestRri, "/sqsearch") || StringUtil.endsWith(requestRri, "/updateSort")))
				|| ex != null) {
			SysLogUtil.saveLog(request, ex == null ? Constants.TYPE_ACCESS : Constants.TYPE_EXCEPTION, ex == null ? "" : ex.getMessage());
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String requestRri = request.getRequestURI();
		String uriPrefix = request.getContextPath();
		String otherRri = requestRri.substring(uriPrefix.length());
		if (StringUtil.startsWith(requestRri, uriPrefix)
				&& (StringUtil.endsWith(requestRri, "/") || StringUtil.endsWith(requestRri, "/login") || StringUtil.startsWith(otherRri, "/api/v1")
						|| StringUtil.startsWith(otherRri, "/images") || StringUtil.startsWith(otherRri, "/jquery")
						|| StringUtil.startsWith(otherRri, "/css") || StringUtil.endsWith(otherRri, "/validateCodeServlet")
						|| StringUtil.endsWith(requestRri, "/index") || StringUtil.endsWith(requestRri, "/sysLogin"))) {
			return true;
		}
		return UserUtil.getUser() == null ? false : true;
	}

}
